/**
 * Created by apple on 2019.01.26.
 */

var express = require('express');
var router = express.Router();

var UserToken = require('../db/user_tokens.js');
var MallDao = require('../dao/mall.js');
var mallRouters = module.exports;

//调用微领商城接口查询用户余额
mallRouters.getBalanceByWL = function(req, res){
    var par = paramAll(req);

    if(!par.user_id){
        return res.json(new ERR('用户手机号不能为空!', 500));
    }

    if(!par.score){
        return res.json(new ERR('充值积分不能为空!', 500));
    }

    if(par.score < 1){
        return res.json(new ERR('充值积分需>1', 500));
    }

    MallDao.getBalanceByWL(par, function(err, data){
        if (err) return res.json(new ERR(err, 400));

        else{
            if(data.code == 200){
                var balance = data.max_change_amount;

                if(par.score > balance){
                    return res.json(new ERR('用户零钱不足!', 500));
                }else{
                    console.log('用户零钱充足，可以继续操作');

                    res.json(new PKG('查询用户零钱余额成功!'));
                }
            }else if(data.code == 440){
                return res.json(new ERR('找不到该用户', 500));
            }
        }
    });
}
router.post('/get_balance_WL', mallRouters.getBalanceByWL);

//调用微领商城接口扣除用户余额
mallRouters.delBalanceByWL = function(req, res){
    var par = paramAll(req);

    if(!par.user_id){
        return res.json(new ERR('用户手机号不能为空!', 500));
    }

    if(!par.score){
        return res.json(new ERR('充值积分不能为空!', 500));
    }

    if(par.score < 1){
        return res.json(new ERR('充值积分需>1', 500));
    }

    MallDao.delBalanceByWL(par, function(err, data){
        if (err) return res.json(new ERR(err, 400));

        else{
            if(data.code == 200){
                return res.json(new ERR('扣除零钱成功', 500));
            }else{
                return res.json(new ERR('扣除零钱失败', 500));
            }
            
        }
    });
}
router.post('/del_balance_WL', mallRouters.delBalanceByWL);

module.exports = router;